<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var w,h
    function dealImage(path, obj, callback){
        var img = new Image();
        img.src = path;
        img.setAttribute('crossOrigin', 'anonymous');
        img.onload = function(){
            var that = this;
            // 默认按比例压缩
             w = that.width,
                h = that.height,
                scale = w / h;
            w = obj.width || w;
            h = obj.height || (w / scale);
            var quality = 0.1;  // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            var base64 = canvas.toDataURL('image/jpg', quality );
            // 回调函数返回base64的值
            callback(base64);
        }
    }
    dealImage("./img/1608277838040348.png", {
// 注意：在pc端可以用绝对路径或相对路径，移动端最好用绝对路径（因为用take photo后的图片路径，我没有试成功（如果有人试成功了可以分享一下经验））
        width : w,
        height:h
    }, function(base){
        console.log(base)
//直接将获取到的base64的字符串，放到一个image标签中就可看到测试后的压缩之后的样式图了
        document.getElementById("transform").src = base;
        console.log("压缩后：" + base.length / 1024 + " " + base);
    })
</script>

</body>
</html>